/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nz.ac.massey.webtech.sseperformance;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletResponse;

/**
 *
 * @author jens dietrich
 */
public class AsyncProcessor implements Runnable {
    private AsyncContext asyncContext = null;
    private boolean stop = false;
    
    
    AsyncProcessor(AsyncContext asyncContext) {
        super();
        this.asyncContext = asyncContext;
        this.asyncContext.addListener(new AsyncListener() {

            public void onComplete(AsyncEvent event) throws IOException {
                System.out.println("async complete");
            }

            public void onTimeout(AsyncEvent event) throws IOException {
                System.out.println("async timeout");
                AsyncProcessor.this.stop=true;
            }

            public void onError(AsyncEvent event) throws IOException {
                System.out.println("async error");
            }

            public void onStartAsync(AsyncEvent event) throws IOException {
                System.out.println("async startup");
            }
        });
    }

    public void run() {
        try {
            ServletResponse response = asyncContext.getResponse();
            PrintWriter out = response.getWriter();
            while (!stop) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AsyncProcessor.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("delivering event");

                EventGenerator.nextEvent(out);
                out.flush();
            }
            System.out.println("closing event stream");
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(AsyncProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    

}
